package servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;

import entities.User;

import utils.UsersHelper;

/**
 * Servlet implementation class Register
 */
@WebServlet("/Register")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String USERNAME = "userName";
	private static final String DISPLAYNAME = "displayName";
	private static final String PASSWORD = "password";
	private static final String REGISTER_RESULT = "result";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		boolean result = UsersHelper.registerNewUser(
				getUser(request)
		);
		response.setContentType("text/json");
		try {
			response.getWriter().write(
					new JSONObject().put(REGISTER_RESULT, result).toString()
					);
		} catch (JSONException e) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
	}
	
	private static User getUser(HttpServletRequest request){
		JSONObject jsonObject ;
		String str = null;
		
		try {
			str = request.getReader().readLine();
			jsonObject = new JSONObject(str);
			return new User(
					jsonObject.optString(USERNAME),
					jsonObject.optString(PASSWORD),
					jsonObject.optString(DISPLAYNAME)
					);
		}catch (JSONException | IOException e){
			e.printStackTrace();
		}
		return null;
	}

}
